import React from 'react';
import { Card, Row, Col, Image, Button, Space, Form, Input, Select, DatePicker, Modal, Pagination, message } from 'antd';
import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';

// AD画廊（模仿 admin-web 的 Adverts.vue）
export default function AdvertsGallery() {
  // 搜索区域
  const [searchForm] = Form.useForm();
  const [search, setSearch] = React.useState({ userName: '', head: '', advertiser: '' });

  // 展示位置字典（模拟 gp_show_type）
  const [showTypeList] = React.useState([
    { label: '全部设备', value: 0 },
    { label: '首页轮播', value: 1 },
    { label: '详情页顶部', value: 2 },
    { label: '底部Banner', value: 3 },
  ]);

  // 列表与分页
  const [loading, setLoading] = React.useState(false);
  const [pageIndex, setPageIndex] = React.useState(1);
  const [pageSize, setPageSize] = React.useState(12);
  const [advertsList, setAdvertsList] = React.useState(() => ([
    {
      id: 1,
      type: 0, // 0 图片, 1 视频
      url: '/vite.svg',
      showImage: '/vite.svg',
      head: '中秋促销',
      display: '展示文案',
      advertiser: '官方',
      price: 0,
      startTime: '2025-09-01 00:00',
      endDate: '2025-10-01 00:00',
      showType: 1,
      createTime: '2025-09-01 12:00',
    },
    {
      id: 2,
      type: 1,
      url: 'https://www.w3schools.com/html/mov_bbb.mp4',
      head: '国庆视频广告',
      display: '视频推广',
      advertiser: '合作商',
      price: 0,
      startTime: '2025-09-20 00:00',
      endDate: '2025-10-08 00:00',
      showType: 3,
      createTime: '2025-09-20 10:20',
    },
    {
      id: 3,
      type: 1,
      url: 'https://media.w3.org/2010/05/sintel/trailer.mp4',
      head: '新品宣传视频',
      display: '视频推广',
      advertiser: '市场部',
      price: 0,
      startTime: '2025-09-25 00:00',
      endDate: '2025-10-15 00:00',
      showType: 2,
      createTime: '2025-09-25 09:00',
    },
    {
      id: 4,
      type: 1,
      url: 'https://media.w3.org/2010/05/bunny/trailer.mp4',
      head: '品牌故事短片',
      display: '视频推广',
      advertiser: '品牌部',
      price: 0,
      startTime: '2025-09-28 00:00',
      endDate: '2025-10-20 00:00',
      showType: 1,
      createTime: '2025-09-28 14:30',
    },
    {
      id: 5,
      type: 1,
      url: 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4',
      head: '节日氛围视频',
      display: '视频推广',
      advertiser: '活动组',
      price: 0,
      startTime: '2025-09-30 00:00',
      endDate: '2025-10-10 00:00',
      showType: 3,
      createTime: '2025-09-30 08:15',
    },
  ]));

  const [adHover, setAdHover] = React.useState('');

  const filtered = React.useMemo(() => {
    let list = advertsList;
    if (search.userName) list = list.filter(i => String(i.userName || '').includes(search.userName));
    if (search.head) list = list.filter(i => String(i.head || '').includes(search.head));
    if (search.advertiser) list = list.filter(i => String(i.advertiser || '').includes(search.advertiser));
    return list;
  }, [advertsList, search]);

  const pageData = React.useMemo(() => {
    const start = (pageIndex - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, pageIndex, pageSize]);

  // 添加/编辑弹窗
  const [dialogAdverts, setDialogAdverts] = React.useState(false);
  const [editRow, setEditRow] = React.useState(null);
  const [adForm] = Form.useForm();

  const openAdd = () => {
    setEditRow(null);
    adForm.resetFields();
    adForm.setFieldsValue({ type: 0, showType: 0, startTime: dayjs(), endDate: dayjs().add(7, 'day') });
    setDialogAdverts(true);
  };
  const openEdit = (row) => {
    setEditRow(row);
    setDialogAdverts(true);
    adForm.setFieldsValue({
      ...row,
      startTime: row.startTime ? dayjs(row.startTime) : null,
      endDate: row.endDate ? dayjs(row.endDate) : null,
    });
  };

  const saveAdvert = async () => {
    const values = await adForm.validateFields();
    const payload = {
      ...values,
      startTime: values.startTime ? values.startTime.format('YYYY-MM-DD HH:mm:ss') : '',
      endDate: values.endDate ? values.endDate.format('YYYY-MM-DD HH:mm:ss') : '',
    };
    if (editRow) {
      setAdvertsList(prev => prev.map(i => (i.id === editRow.id ? { ...i, ...payload } : i)));
      message.success('广告已更新');
    } else {
      const id = Math.max(0, ...advertsList.map(i => i.id)) + 1;
      const newItem = { id, createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), ...payload };
      setAdvertsList(prev => [newItem, ...prev]);
      message.success('广告已添加');
    }
    setDialogAdverts(false);
  };

  const delOneAdverts = (row) => {
    Modal.confirm({
      title: '删除确认',
      content: `确定删除广告「${row.head || '无标题'}」吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setAdvertsList(prev => prev.filter(i => i.id !== row.id));
        message.success('删除成功');
      },
    });
  };

  const formatterShowType = (row) => {
    const item = showTypeList.find(s => s.value === Number(row.showType));
    return item ? item.label : row.showType;
  };

  const onSubmitSearch = async () => {
    const values = await searchForm.validateFields();
    setSearch(values);
    setPageIndex(1);
  };
  const resetSearch = () => {
    searchForm.resetFields();
    setSearch({ userName: '', head: '', advertiser: '' });
    setPageIndex(1);
  };

  return (
    <div className="adverts jt-wrap">
      {/* 搜索与新增 */}
      <div className="el-search vue-top-padding" style={{ marginBottom: 12 }}>
        <div className="el-left" style={{ display: 'inline-block' }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={openAdd}>新增广告</Button>
        </div>
        <div className="el-right" style={{ float: 'right' }}>
          <Form form={searchForm} layout="inline" initialValues={search}>
            <Form.Item name="userName">
              <Input placeholder="用户昵称" allowClear />
            </Form.Item>
            <Form.Item name="head">
              <Input placeholder="标题" allowClear />
            </Form.Item>
            <Form.Item name="advertiser">
              <Input placeholder="广告商" allowClear />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" onClick={onSubmitSearch}>搜索</Button>
                <Button onClick={resetSearch}>重置</Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
      </div>

      {/* 画廊列表 */}
      <div className="table vue-padding radius" style={{ overflow: 'auto' }}>
        <Row gutter={20} justify="start" wrap>
          {pageData.length > 0 && pageData.map((item) => (
            <Col key={item.id} xl={4} lg={6} sm={8} xs={24}>
              <Card styles={{ body: { padding: 0 } }} hoverable>
                <div className="content" style={{ position: 'relative', overflow: 'hidden' }}>
                  {item.type === 0 ? (
                    <Image
                      src={item.url}
                      preview={{ visible: false }}
                      style={{ width: '100%', height: 260, objectFit: 'cover', cursor: 'pointer' }}
                    />
                  ) : (
                    <video src={item.url} controls preload="none" style={{ width: '100%', height: 260 }} onError={() => message.warning('视频加载失败或被远程取消')} />
                  )}
                  {adHover === item.id && (
                    <div className="info" style={{ position: 'absolute', padding: 20, color: 'rgba(255,255,255,0.9)', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.6)' }}>
                      <div className="info-container" style={{ position: 'relative', top: '50%', transform: 'translateY(-50%)' }}>
                        <div className="ad-info" style={{ margin: '10px 0' }}>{item.startTime}</div>
                        <div className="ad-info" style={{ margin: '10px 0' }}>{item.endDate}</div>
                        <div className="ad-info" style={{ margin: '10px 0' }}>{formatterShowType(item)}</div>
                      </div>
                    </div>
                  )}
                </div>
                <div style={{ padding: 14 }}>
                  <div
                    className="title"
                    style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}
                    onMouseOver={() => setAdHover(item.id)}
                    onMouseOut={() => setAdHover('')}
                  >
                    {item.head || '无标题'}
                  </div>
                  <div className="bottom clearfix" style={{ marginTop: 12, display: 'flex', justifyContent: 'space-between' }}>
                    <time className="time">{item.createTime}</time>
                    <div className="btn-group" style={{ display: 'flex', gap: 8 }}>
                      <Button type="text" icon={<EditOutlined />} onClick={() => openEdit(item)} />
                      <Button type="text" danger icon={<DeleteOutlined />} onClick={() => delOneAdverts(item)} />
                    </div>
                  </div>
                </div>
              </Card>
            </Col>
          ))}
        </Row>

        {/* 分页 */}
        <div style={{ marginTop: 12, display: 'flex', justifyContent: 'center' }}>
          <Pagination
            current={pageIndex}
            pageSize={pageSize}
            total={filtered.length}
            showSizeChanger
            pageSizeOptions={[12, 24, 36]}
            onChange={(pi, ps) => { setPageIndex(pi); setPageSize(ps); }}
          />
        </div>
      </div>

      {/* 添加/编辑广告弹窗 */}
      <Modal
        title={editRow ? '编辑广告' : '新增广告'}
        open={dialogAdverts}
        onCancel={() => setDialogAdverts(false)}
        onOk={saveAdvert}
        okText="保存"
        cancelText="取消"
        width={720}
      >
        <Form form={adForm} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="广告类型" name="type" rules={[{ required: true }]}>
                <Select options={[{ label: '图片', value: 0 }, { label: '视频', value: 1 }]} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="展示位置" name="showType" rules={[{ required: true }]}>
                <Select options={showTypeList.map(d => ({ label: d.label, value: d.value }))} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item label="资源地址（图片/视频URL）" name="url" rules={[{ required: true, message: '请输入资源地址' }]}> 
                <Input placeholder="请输入图片或视频的URL" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="标题" name="head"> 
                <Input placeholder="标题" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="广告商" name="advertiser"> 
                <Input placeholder="广告商" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="开始时间" name="startTime"> 
                <DatePicker showTime style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="结束时间" name="endDate"> 
                <DatePicker showTime style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item label="备注" name="notes"> 
                <Input.TextArea rows={3} placeholder="备注" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
}